package com.geektimestudy.week7.config;

import com.geektimestudy.week7.source.DynamicDataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class MyBatisConfig {
  @Bean("master")
  @Primary
  @ConfigurationProperties(prefix = "spring.datasource.master")
  public DataSource master() {
    return DataSourceBuilder.create().build();
  }

  @Bean("slave")
  @ConfigurationProperties(prefix = "spring.datasource.slave")
  public DataSource slave() {
    return DataSourceBuilder.create().build();
  }

  @Bean("dynamicDataSource")
  public DataSource dynamicDataSource() {
    DynamicDataSource dynamicDataSource = new DynamicDataSource();
    Map<Object, Object> dataSourceMap = new HashMap<>(2);
    dataSourceMap.put("master", master());
    dataSourceMap.put("slave", slave());
    // 将 master 数据源作为默认指定的数据源
    dynamicDataSource.setDefaultDataSource(master());
    // 将 master 和 slave 数据源作为指定的数据源
    dynamicDataSource.setDataSources(dataSourceMap);
    return dynamicDataSource;
  }
}
